package main

import (
	"bufio"
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"os"
)

func readLastNLines(fileName string, n int) ([]string, error) {
	file, err := os.Open(fileName)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	lines := make([]string, 0)

	for scanner.Scan() {
		lines = append(lines, scanner.Text())
		if len(lines) > n {
			lines = lines[1:]
		}
	}

	if scanner.Err() != nil {
		return nil, scanner.Err()
	}

	return lines, nil
}

func handleWebSocketConnection() http.HandlerFunc {

	return func(w http.ResponseWriter, r *http.Request) {
		q := r.URL.Query()
		serviceName := q.Get("serviceName")
		action := q.Get("action")
		wsj, exit := serviceMap[serviceName]
		//判断b是否为空
		if !exit {
			filePath := path + "api.out"
			broadcaster := newBroadcaster()
			go broadcaster.run(serviceName + action)
			go broadcaster.tailFile(filePath)
			wsj.ServiceInfo.FilePath = filePath
			wsj.ServiceInfo.Lines = 10000
			wsj.Broadcaster = broadcaster
			serviceMap[serviceName] = wsj
			ws, err := upgrader.Upgrade(w, r, nil)
			if err != nil {
				log.Println(err)
				return
			}
			client := &Client{socket: ws, send: make(chan []byte)}
			broadcaster.register <- client
			go broadcaster.initialRead(client, wsj.ServiceInfo.FilePath, wsj.ServiceInfo.Lines)

			go func() {
				defer func() {
					broadcaster.unregister <- client
					ws.Close()
				}()

				for {
					_, _, err := ws.ReadMessage()
					if err != nil {
						broadcaster.unregister <- client
						ws.Close()
						break
					}
				}
			}()

			go func() {
				defer ws.Close()
				for {
					message, ok := <-client.send
					if !ok {
						ws.WriteMessage(websocket.CloseMessage, []byte{})
						return
					}
					ws.WriteMessage(websocket.TextMessage, message)
				}
			}()
		} else {
			client, isExit := wsj.Broadcaster.clients[serviceName+action]
			if !isExit {
				go wsj.Broadcaster.run(serviceName + action)
				ws, err := upgrader.Upgrade(w, r, nil)
				if err != nil {
					log.Println(err)
					return
				}

				client = &Client{socket: ws, send: make(chan []byte)}
				broadcaster := wsj.Broadcaster

				wsj.Broadcaster.register <- client
				go broadcaster.initialRead(client, wsj.ServiceInfo.FilePath, wsj.ServiceInfo.Lines)

				go func() {
					defer func() {
						broadcaster.unregister <- client
						ws.Close()
					}()

					for {
						_, _, err := ws.ReadMessage()
						if err != nil {
							broadcaster.unregister <- client
							ws.Close()
							break
						}
					}
				}()

				go func() {
					defer ws.Close()
					for {
						message, ok := <-client.send
						if !ok {
							ws.WriteMessage(websocket.CloseMessage, []byte{})
							return
						}
						ws.WriteMessage(websocket.TextMessage, message)
					}
				}()
			}
			fmt.Println("client:", client)
		}

	}
}
